<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="金额" prop="amount">
        <el-input
            v-model="queryParams.amount"
            placeholder="请输入金额"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="下单时间" prop="orderTime">
        <el-date-picker clearable
                        v-model="queryParams.orderTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择下单时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="salesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单ID" align="center" prop="orderId" />
      <el-table-column label="店铺ID" align="center" prop="storeId" />
      <el-table-column label="金额" align="center" prop="amount" />
      <el-table-column label="下单时间" align="center" prop="orderTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改存储销售记录的对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="salesRef" :model="form" :rules="rules" label-width="80px">
        <el-divider content-position="center">收入查询信息</el-divider>
        <el-row :gutter="10" class="mb8">
        </el-row>
        <el-table :data="revenueRecordsList" :row-class-name="rowRevenueRecordsIndex" @selection-change="handleRevenueRecordsSelectionChange" ref="revenueRecords">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="收入类型" prop="incomeType" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.incomeType" placeholder="请选择收入类型">
                <el-option
                    v-for="dict in income_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="amount" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.amount" placeholder="请输入金额" />
            </template>
          </el-table-column>
          <el-table-column label="收入日期" prop="incomeDate" width="240">
            <template #default="scope">
              <el-date-picker clearable
                              v-model="scope.row.incomeDate"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择收入日期">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="店铺ID" prop="storeId" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.storeId" placeholder="请输入店铺ID" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Sales">
import { listSales, getSales, delSales, addSales, updateSales } from "@/api/sale/sale";

const { proxy } = getCurrentInstance();
const { income_type } = proxy.useDict('income_type');

const salesList = ref([]);
const revenueRecordsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedRevenueRecords = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    amount: null,
    orderTime: null,
  },
  rules: {
    storeId: [
      { required: true, message: "店铺ID不能为空", trigger: "blur" }
    ],
    amount: [
      { required: true, message: "金额不能为空", trigger: "blur" }
    ],
    orderTime: [
      { required: true, message: "下单时间不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询存储销售记录的列表 */
function getList() {
  loading.value = true;
  listSales(queryParams.value).then(response => {
    salesList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    storeId: null,
    amount: null,
    orderTime: null,
    deleted: null
  };
  revenueRecordsList.value = [];
  proxy.resetForm("salesRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orderId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加存储销售记录的";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _orderId = row.orderId || ids.value
  getSales(_orderId).then(response => {
    form.value = response.data;
    revenueRecordsList.value = response.data.revenueRecordsList;
    open.value = true;
    title.value = "修改存储销售记录的";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["salesRef"].validate(valid => {
    if (valid) {
      form.value.revenueRecordsList = revenueRecordsList.value;
      if (form.value.orderId != null) {
        updateSales(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSales(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _orderIds = row.orderId || ids.value;
  proxy.$modal.confirm('是否确认删除存储销售记录的编号为"' + _orderIds + '"的数据项？').then(function() {
    return delSales(_orderIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 收入查询序号 */
function rowRevenueRecordsIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 收入查询添加按钮操作 */
function handleAddRevenueRecords() {
  let obj = {};
  obj.incomeType = "";
  obj.amount = "";
  obj.incomeDate = "";
  obj.storeId = "";
  revenueRecordsList.value.push(obj);
}

/** 收入查询删除按钮操作 */
function handleDeleteRevenueRecords() {
  if (checkedRevenueRecords.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的收入查询数据");
  } else {
    const revenueRecordss = revenueRecordsList.value;
    const checkedRevenueRecordss = checkedRevenueRecords.value;
    revenueRecordsList.value = revenueRecordss.filter(function (item) {
      return checkedRevenueRecordss.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleRevenueRecordsSelectionChange(selection) {
  checkedRevenueRecords.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('sale/sale/export', {
    ...queryParams.value
  }, `sales_${new Date().getTime()}.xlsx`)
}

getList();
</script>
